package com.pshare.util;

import java.lang.reflect.Method;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;


public class MapUtil {
	
    private static final Object[] EMPTY_ARRAY ={};
    
	
	   /**
     * 将一个bean转换成map
     * @param map
     * @param bean
     * @return
     */
    public static Map populateMap(Map map, Object bean){
        return populateMap(map, bean,null);
    }
    
    /**
     * 假设prefix=detail.，bean带有一个属性name，则map中将有一个项：
     * key=detail.name，value为bean的name属性值。
     */
    public static Map populateMap(Map map, Object bean, String prefix) {
        boolean withoutPrefix = StringUtils.isBlank(prefix);
        
        try {
            Method[] methods = bean.getClass().getMethods();
            for (int i = 0; i < methods.length; i++) {
                String methodName = methods[i].getName();
                Class[] pts = methods[i].getParameterTypes();
                Class rt = methods[i].getReturnType();
                
                if (methodName.startsWith("get") && pts.length == 0 && !Void.class.equals(rt)) {
                    String propName = Character.toLowerCase(methodName.charAt(3)) + methodName.substring(4);
                    if ("class".equals(propName)) {
                        continue;
                    }
                    
                    String key = withoutPrefix ? propName : prefix + propName;
                    
                    Object value = methods[i].invoke(bean, EMPTY_ARRAY);
                    if (value != null) {
                        map.put(key, value);
                    }
                }
            }
            
            return map;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

}